<template>
  <div class="app-container">
    <div class="search-bar">
      <el-card shadow="never" style="margin-bottom: 5px">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="主键" prop="id">
            <el-input
              v-model="queryParams.id"
              placeholder="主键"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item label="时间" prop="time">
            <el-date-picker
              v-model="queryParams.time"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="SKU" prop="sku">
            <el-input
              v-model="queryParams.sku"
              placeholder="SKU"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item label="品牌" prop="brand">
            <el-input
              v-model="queryParams.brand"
              placeholder="品牌"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item label="三级类别" prop="categoryLevel3">
            <el-input
              v-model="queryParams.categoryLevel3"
              placeholder="三级类别"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item label="店铺简称" prop="shopShortName">
            <el-input
              v-model="queryParams.shopShortName"
              placeholder="店铺简称"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <template #icon><Search /></template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon><Refresh /></template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['datacenter:productsingle:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['datacenter:productsingle:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>

        <!-- Excel操作按钮 -->
        <el-button
          type="primary"
          @click="handleExportExcel()"
        >
          <template #icon><Download /></template>
          导出Excel
        </el-button>
        <el-button
          type="primary"
          @click="handleImportExcel()"
        >
          <template #icon><Upload /></template>
          导入Excel
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="主键"
          prop="id"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="time"
          label="时间"
          prop="time"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="productName"
          label="商品名称"
          prop="productName"
          min-width="200"
          align="center"
        />
        <el-table-column
          key="sku"
          label="SKU"
          prop="sku"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="brand"
          label="品牌"
          prop="brand"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categoryLevel1"
          label="一级类别"
          prop="categoryLevel1"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categoryLevel2"
          label="二级类别"
          prop="categoryLevel2"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categoryLevel3"
          label="三级类别"
          prop="categoryLevel3"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="shopShortName"
          label="店铺简称"
          prop="shopShortName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="operationMode"
          label="经营模式"
          prop="operationMode"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="pageViews"
          label="浏览量"
          prop="pageViews"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="visitorCount"
          label="访客数"
          prop="visitorCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="avgPageViewsPerVisitor"
          label="人均浏览量"
          prop="avgPageViewsPerVisitor"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="avgStayTime"
          label="平均停留时长"
          prop="avgStayTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="transactionUserCount"
          label="成交人数"
          prop="transactionUserCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="conversionRate"
          label="成交转化率"
          prop="conversionRate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="transactionAmount"
          label="成交金额"
          prop="transactionAmount"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['datacenter:productsingle:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['datacenter:productsingle:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 单品跟进表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="时间" prop="time">
          <el-date-picker
            v-model="formData.time"
            type="datetime"
            placeholder="时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="formData.productName"
            placeholder="商品名称"
          />
        </el-form-item>

        <el-form-item label="SKU" prop="sku">
          <el-input
            v-model="formData.sku"
            placeholder="SKU"
          />
        </el-form-item>

        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model="formData.brand"
            placeholder="品牌"
          />
        </el-form-item>

        <el-form-item label="一级类别" prop="categoryLevel1">
          <el-input
            v-model="formData.categoryLevel1"
            placeholder="一级类别"
          />
        </el-form-item>

        <el-form-item label="二级类别" prop="categoryLevel2">
          <el-input
            v-model="formData.categoryLevel2"
            placeholder="二级类别"
          />
        </el-form-item>

        <el-form-item label="三级类别" prop="categoryLevel3">
          <el-input
            v-model="formData.categoryLevel3"
            placeholder="三级类别"
          />
        </el-form-item>

        <el-form-item label="店铺简称" prop="shopShortName">
          <el-input
            v-model="formData.shopShortName"
            placeholder="店铺简称"
          />
        </el-form-item>

        <el-form-item label="经营模式" prop="operationMode">
          <el-input
            v-model="formData.operationMode"
            placeholder="经营模式"
          />
        </el-form-item>

        <el-form-item label="浏览量" prop="pageViews">
          <el-input
            v-model="formData.pageViews"
            placeholder="浏览量"
          />
        </el-form-item>

        <el-form-item label="访客数" prop="visitorCount">
          <el-input
            v-model="formData.visitorCount"
            placeholder="访客数"
          />
        </el-form-item>

        <el-form-item label="人均浏览量" prop="avgPageViewsPerVisitor">
          <el-input
            v-model="formData.avgPageViewsPerVisitor"
            placeholder="人均浏览量"
          />
        </el-form-item>

        <el-form-item label="平均停留时长" prop="avgStayTime">
          <el-input
            v-model="formData.avgStayTime"
            placeholder="平均停留时长"
          />
        </el-form-item>

        <el-form-item label="成交人数" prop="transactionUserCount">
          <el-input
            v-model="formData.transactionUserCount"
            placeholder="成交人数"
          />
        </el-form-item>

        <el-form-item label="成交转化率" prop="conversionRate">
          <el-input
            v-model="formData.conversionRate"
            placeholder="成交转化率"
          />
        </el-form-item>

        <el-form-item label="成交金额" prop="transactionAmount">
          <el-input
            v-model="formData.transactionAmount"
            placeholder="成交金额"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入Excel对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入Excel"
      width="500px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :limit="5"
        :on-exceed="handleExceed"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :show-file-list="true"
        accept=".xlsx"
        multiple
        drag
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">拖拽文件到此处，或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>支持批量上传，最多5个.xlsx格式文件</span>
            <el-button type="primary" link @click="handleDownloadTemplate">下载模板</el-button>
          </div>
        </template>
      </el-upload>
      <div v-if="importResult" class="mt-15">
        <el-alert
          :title="`导入结果: 成功${importResult.validCount}条，失败${importResult.invalidCount}条，总计${importResult.validCount + importResult.invalidCount}条`"
          :type="importResult.invalidCount > 0 ? 'warning' : 'success'"
          show-icon
        />
        <el-collapse v-if="importResult.messageList && importResult.messageList.length > 0" class="mt-10px">
          <el-collapse-item title="错误详情">
            <ul class="error-list">
              <li v-for="(msg, index) in importResult.messageList" :key="index" class="text-red-500">
                {{ msg }}
              </li>
            </ul>
          </el-collapse-item>
        </el-collapse>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="uploadLoading" @click="submitImport">
            批量导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete, Search, Refresh, Download, Upload, Edit } from "@element-plus/icons-vue";
import ProductsingleAPI, { ProductsinglePageVO, ProductsingleForm, ProductsinglePageQuery } from "@/api/system/productsingle";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ProductsinglePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 单品跟进表格数据
const pageData = ref<ProductsinglePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 单品跟进表单数据
const formData = reactive<ProductsingleForm>({});

// 导入对话框相关变量
const importDialogVisible = ref(false);
const importFiles = ref<File[]>([]);
const importResult = ref<ExcelResult | null>(null);
const uploadLoading = ref(false);
const uploadRef = ref();

// 表单校验规则
const rules = reactive({
  productName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  sku: [{ required: true, message: "请输入SKU", trigger: "blur" }],
  brand: [{ required: true, message: "请输入品牌", trigger: "blur" }],
});

/** 查询单品跟进 */
function handleQuery() {
  loading.value = true;
  ProductsingleAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置单品跟进查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开单品跟进弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改单品跟进";
    ProductsingleAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增单品跟进";
    Object.assign(formData, {});
  }
}

/** 提交单品跟进表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ProductsingleAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ProductsingleAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭单品跟进弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value?.resetFields();
  dataFormRef.value?.clearValidate();
  Object.assign(formData, {});
}

/** 删除单品跟进 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    ProductsingleAPI.deleteByIds(ids)
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .finally(() => (loading.value = false));
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
}

// 导出Excel处理函数
const handleExportExcel = () => {
  ProductsingleAPI.exportExcel(queryParams).then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
    const fileName = `单品跟进数据_${new Date().getTime()}.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
    ElMessage.success('导出成功');
  }).catch(() => {
    ElMessage.error('导出失败');
  });
};

// 导入Excel处理函数
const handleImportExcel = () => {
  importDialogVisible.value = true;
  importFiles.value = [];
  importResult.value = null;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 下载模板处理函数
const handleDownloadTemplate = () => {
  ProductsingleAPI.downloadTemplate().then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
    const fileName = `单品跟进数据导入模板.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
    ElMessage.success('模板下载成功');
  }).catch(() => {
    ElMessage.error('模板下载失败');
  });
};

// 文件超出限制回调
const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件');
};

// 文件状态改变时的回调
const handleFileChange = (file: any) => {
  importFiles.value.push(file.raw);
};

// 文件移除时的回调
const handleFileRemove = (file: any) => {
  const index = importFiles.value.findIndex(f =>
    f.name === file.name && f.size === file.size
  );
  if (index !== -1) {
    importFiles.value.splice(index, 1);
  }
};

// 提交导入
const submitImport = async () => {
  if (importFiles.value.length === 0) {
    ElMessage.warning('请先选择要上传的Excel文件');
    return;
  }

  uploadLoading.value = true;

  try {
    let totalValidCount = 0;
    let totalInvalidCount = 0;
    let allMessages: string[] = [];

    // 依次处理每个文件
    for (const file of importFiles.value) {
      const result = await ProductsingleAPI.importExcel(file);
      totalValidCount += result.validCount;
      totalInvalidCount += result.invalidCount;
      if (result.messageList) {
        allMessages = allMessages.concat(result.messageList.map(msg => `[${file.name}] ${msg}`));
      }
    }

    // 更新导入结果
    importResult.value = {
      validCount: totalValidCount,
      invalidCount: totalInvalidCount,
      messageList: allMessages,
      success: totalInvalidCount === 0
    };

    if (totalInvalidCount === 0) {
      ElMessage.success(`批量导入成功，共导入${totalValidCount}条数据`);
      setTimeout(() => {
        importDialogVisible.value = false;
      }, 2000);
    } else {
      ElMessage.warning(`导入完成，成功${totalValidCount}条，失败${totalInvalidCount}条`);
    }

    // 刷新表格数据
    handleQuery();
  } catch (error) {
    console.error('导入出错:', error);
    ElMessage.error('导入失败，请检查文件格式是否正确');
  } finally {
    uploadLoading.value = false;
  }
};

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.error-list {
  list-style-type: disc;
  margin-left: 20px;
}

.mt-15 {
  margin-top: 15px;
}

.mt-10px {
  margin-top: 10px;
}

.text-red-500 {
  color: #ef4444;
}

.mb-10px {
  margin-bottom: 10px;
}
</style> 